import React, { Component } from 'react';
import PDF from 'react-pdf-js';

class Pdf extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 1,
            src: this.props.media.src
        };
    }

    componentWillUnmount() {
        clearInterval(this.interval)
        clearInterval(this.timer)
    }

    componentWillReceiveProps(nextProps) {
        clearInterval(this.interval)
        clearInterval(this.timer)
        this.setState ({
            page:1,
            src: nextProps.media.src
        }) 
    }

    onEnded = id=> {
        this.props.startNextMedia(id)
    }
    
    onDocumentComplete = pages=> {
        console.log("总页数", pages)
        if (pages > 1) {
            this.timer=setInterval(() => {
                let page = this.state.page + 1
                if (page <= pages) {
                    this.setState({ page: page });
                } else {
                    this.onEnded(this.props.media.id)
                }
            }, this.props.media.playTime * 1000)

        } else {
            this.interval = setInterval(this.onEnded, this.props.media.playTime * 1000)
        }

    }

    render() {
      let src= this.state.src;
      if(!src)return false;
        return (
            <div className="pdf" style={{ "backgroundImage": "url(static/image/bg.png)", }}>
                <PDF 
                    key={this.props.media.id}
                    file={src}
                    scale={2}
                    onDocumentComplete={this.onDocumentComplete}
                    page={this.state.page}
                />
            </div>
        )
    }
}

export default Pdf;
